﻿using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Domain.DomainRepository;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Domain.LogDomain;
using Zocono.WCS.Domain.PlcBytesObject;
using Zocono.WCS.Domain.PlcConnectPoolDomain;
using Zocono.WCS.Domain.ProcessModuleDomain;
using Zocono.WCS.Infrastructure.ApllicationDto.Enums;
using Zocono.WCS.Infrastructure.ApllicationDto.WCSTaskDto;
using Zocono.WCS.Infrastructure.PlcCommon;
using Zocono.WCS.WMSApiDomain.WebApi;

namespace Zocono.WCS.Domain.EquipmentProcessDomain.PlanarGeneralMessage
{
    /// <summary>
    /// 目标位请求（生成新任务） 没用到
    /// </summary>
    public class TargetRequestService : IPlanarGeneralPlcActionProcessService
    {

        private readonly ISnowflake _snowflake;
        private readonly IPlcConnectionPool _plcConnectionPool;
        private readonly IWorkTaskInfoRepository _workTaskInfoRepository;
        private readonly IPlcWriteDbInfoRepository _plcWriteDbInfoRepository;
        private readonly IPlcConnectionInfoRepository _PlcConnectionInfoRepository;
        private readonly IPlcPointInfoRepositpry _IPlcPointInfoRepositpry;
        private readonly IPlcConnectionStateInfoRepository _IPlcConnectionStateInfoRepository;
        private readonly IRunLogInfoService _IRunLogInfoService;
        public TargetRequestService(ISnowflake snowflake,
            IPlcConnectionPool plcConnectionPool, IWorkTaskInfoRepository workTaskInfoRepository
            , IPlcWriteDbInfoRepository plcWriteDbInfoRepository
            , IPlcPointInfoRepositpry plcPointInfoRepositpry
             , IPlcConnectionInfoRepository plcConnectionInfoRepository
           , IPlcConnectionStateInfoRepository plcConnectionStateInfoRepository
            , IRunLogInfoService runLogInfoService)
        {
            _snowflake = snowflake;
            _plcConnectionPool = plcConnectionPool;
            _workTaskInfoRepository = workTaskInfoRepository;
            _plcWriteDbInfoRepository = plcWriteDbInfoRepository;
            _PlcConnectionInfoRepository = plcConnectionInfoRepository;
            _IPlcPointInfoRepositpry = plcPointInfoRepositpry;
            _IPlcConnectionStateInfoRepository = plcConnectionStateInfoRepository;
            _IRunLogInfoService = runLogInfoService;
        }
        public async Task ProcessActionMessageAsync(BytesObjectBase plcActionMessage, BytesObjectBase wcsActionMessage, EquipmentDbObject planarEquipmentDbObject)
        {
            var plcMessage = plcActionMessage as PlanarGeneralPlcActionBO;
            var wcsMessage = wcsActionMessage as PlanarGeneralWcsActionBO;
            plcMessage.PalletBarcode.Trim();
            RunLogInfo runLogInfo = new RunLogInfo();
            runLogInfo.ContainerBarcode = plcMessage.PalletBarcode;
            runLogInfo.EquipmentCode = plcMessage.EquipmentCode;
            runLogInfo.RunType = "目标位请求";

            #region 验证是否具备执行业务条件

            if (wcsMessage == null)
            {
                runLogInfo.RunLog = $"报警：设备报警";
                //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                return;
            }

            //获取PLC连接池的连接
            PlcConnectionS7 plcConn = _plcConnectionPool.S7GetWritePlcConnection(plcMessage.PlcConnectionID);
            if (plcMessage == null)
            {
                runLogInfo.RunLog = $"获取PLC连接失败IP:{plcConn.IP}";
                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                return;
            }

            //查看plc是否连接上
            var plcConnState = await _IPlcConnectionStateInfoRepository.GetFirstAsync(l=>l.PlcConnectionID==plcMessage.PlcConnectionID && l.Connected == true);
            if (plcConnState == null)
            {
                runLogInfo.RunLog = $"PLC连接失败IP:{plcConn.IP}:连接状态为false";
                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                return;
            }

            //获取plc写入配置
            var writeConfig = await _plcWriteDbInfoRepository.GetFirstAsync(l => l.EquipmentCode == plcMessage.EquipmentCode&&l.ObjectType==plcMessage.ObjectType);
            if (writeConfig==null)
            {
                runLogInfo.RunLog = "获取PLC写入配置失败，结果为空";
                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                return;
            }
            #endregion


            #region 构造写入报文类及相关验证

            //构造写入报文类
            var writeBo = new PlanarGeneralWriteWcsAction(
                plcMessage.PlcConnectionID,
                writeConfig.ID,
                writeConfig.DbCode,
                writeConfig.DbStart,
                plcMessage.ObjectType,
                plcMessage.EquipmentCode.ToInt32(),
                plcMessage.ActionType,
                plcMessage.ToEquipmentCode,
                plcMessage.TaskCode,
                plcMessage.PalletBarcode,
                plcMessage.PalletType,
                plcMessage.AlrmCode
                );
            //托盘类型
            switch (writeBo.PalletBarcode.Substring(1, 1))
            {
                case "A":
                    writeBo.PalletType = 1;
                    break;
                case "B":
                    writeBo.PalletType = 2;
                    break;
                case "C":
                    writeBo.PalletType = 3;
                    break;
            }

            //托盘号不存在 写入握手类型0报警10
            if (string.IsNullOrEmpty(plcMessage.PalletBarcode))
            {

                runLogInfo.RunLog = "PLC托盘信息不存在！";
                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                writeBo.ActionType = 0;
                writeBo.AlrmCode = 10;
                var writeBl = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());

                if (writeBl == false)
                {
                    runLogInfo.RunLog = $"PLC(IP{plcConn.IP}：写入报文失败";
                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                }
                else
                {
                    runLogInfo.RunLog = $"PLC(IP{plcConn.IP}：写入报文成功";
                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);

                }
                return;
            }

            #endregion

            #region 查看任务是否已存在若存在则处理业务


            var exp = Expressionable.Create<WorkTaskInfo>();
            exp.AndIF(true, l => l.PalletCode == plcMessage.PalletBarcode && (l.TaskState == EnumTaskState.Initial || l.TaskState == EnumTaskState.Executing));
            var wcsWorkTaskInfo = await _workTaskInfoRepository.GetFirstAsync(exp.ToExpression());
            //根据托盘是否存在其它的任务 && 起点位置是否相同判断，存在则写入正常报文Return
            if (wcsWorkTaskInfo != null && wcsWorkTaskInfo.CurrentFromEquipment == plcMessage.EquipmentCode)
            {

                runLogInfo.RunLog = $"请求分配重复:任务号：{wcsWorkTaskInfo.TaskCode}任务已存在";
                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);

                //针对wcs任务为初始化的处理成执行中并同步更新wms任务状态
                if (wcsWorkTaskInfo.TaskState == EnumTaskState.Initial || wcsWorkTaskInfo.TaskState == EnumTaskState.Executing)
                {
                    wcsWorkTaskInfo.TaskState = EnumTaskState.Executing;
                    wcsWorkTaskInfo.UpdateTime = DateTime.Now;
                    wcsWorkTaskInfo.CurrentDetailTaskState = EnumDetailTaskState.Executing;
                    try
                    {
                        //同步更新wms任务状态
                        var flag = await WCSMessageWithWMSApi.WCSUpdateWMStaskStateAndProcessTaskStateAsync(wcsWorkTaskInfo.WmsTaskCode, (int)EnumTaskState.Executing);
                        if (flag)
                        {
                            wcsWorkTaskInfo.UploadWmsState = EnumUploadWmsState.Succeed;
                            wcsWorkTaskInfo.UploadWmsTime = DateTime.Now;
                        }
                    }
                    catch (Exception ex)
                    {

                        runLogInfo.RunLog = $"wms任务号{wcsWorkTaskInfo.TaskCode}同步状态更新失败";
                        await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                    }
                    //更新wcs任务状态为执行中
                    await _workTaskInfoRepository.UpdateAsync(wcsWorkTaskInfo);
                }

                //写入正常报文
                writeBo.TaskCode = wcsWorkTaskInfo.TaskCode;
                writeBo.PalletBarcode = wcsWorkTaskInfo.PalletCode;
                writeBo.ToEquipmentCode = wcsWorkTaskInfo.CurrentToEquipment.ToInt32();
                var writeBl = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                if (!writeBl)
                {
                    runLogInfo.RunLog = $"请求分配重复:写入正常报文报文失败";
                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);

                    return;
                }
                else
                {
                    runLogInfo.RunLog = $"请求分配重复:写入正常报文报文成功";
                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);

                }
                return;
            }

            #endregion



            #region wcs托盘搬运任务逻辑处理
            WmsTaskInfoDto workTaskDto = null;
            try
            {
                //向wms读取巷道分配任务
                WMSApiDomain.WebApi.HeaderResult<WmsTaskInfoDto> res = await WCSMessageWithWMSApi.WCSCreatUploadWarehouseWMSTaskAsync(plcMessage.PalletBarcode, plcMessage.EquipmentCode);
                if (res.IsSucceed)
                {
                    workTaskDto = res.Result;
                }
                else
                {
                    var msg = res.Message;
                    runLogInfo.RunLog = $"向Wms请求任务失败:{msg}";
                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                    if (msg.Contains("没有配置工位信息"))
                        writeBo.AlrmCode = 20;
                    if (msg.Contains("NG分选机出口扫码位置流程报错"))
                        writeBo.AlrmCode = 21;
                    if (msg.Contains("不存在业务类型数据"))
                        writeBo.AlrmCode = 22;
                    if (msg.Contains("扫码位置流程报错"))
                        writeBo.AlrmCode = 23;
                    if (msg.Contains("投入口无法查询对应的流程"))
                        writeBo.AlrmCode = 24;
                    if (msg.Contains("没有绑定流程参数"))
                        writeBo.AlrmCode = 25;
                    if (msg.Contains("节点数据配置异常"))
                        writeBo.AlrmCode = 26;
                    if (msg.Contains("未配置巷道分配关联数据"))
                        writeBo.AlrmCode = 27;
                    if (msg.Contains("未配置巷道分配关联明细数据"))
                        writeBo.AlrmCode = 28;
                    if (msg.Contains("未配置巷道分组指针"))
                        writeBo.AlrmCode = 29;
                    if (msg.Contains("没有可用巷道"))
                        writeBo.AlrmCode = 30;

                    writeBo.ActionType = 0;
                    var writeBl = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                    return;
                }

            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("at") && ex.Message.Contains("System.Exception:"))
                {

                    var msg = ex.Message.Split("at").First().Split("System.Exception:");
                    runLogInfo.RunLog = $"向Wms请求任务失败:{msg[1]}";

                }
                else
                {
                    var msg = ex.Message.Length > 150 ? ex.Message.Substring(0, 100) : ex.Message;
                    runLogInfo.RunLog = $"向Wms请求任务失败:{msg}";
                }
                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
            }

            //wms请求失败处理 写入100报警握手类型
            if (workTaskDto == null)
            {

                runLogInfo.RunLog = $"向Wms请求任务失败WMS返回空";
                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                writeBo.ActionType = 0;
                writeBo.AlrmCode = 100;
                var writeBl = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                if (writeBl == false)
                {
                    runLogInfo.RunLog = $"向Wms请求任务失败：向PLC写入报文失败";
                }
                else
                {
                    runLogInfo.RunLog = $"向Wms请求任务失败：向PLC写入报文成功";
                }
                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                return;
            }

            //WorkTaskInfo数据补全
            var workTaskInfo = new WorkTaskInfo();

            long id = _snowflake.GetId();//雪花ID
            workTaskInfo.ID = id;
            //wcs任务code从wmstaskcode日开始截取
            int.TryParse(workTaskDto.TaskCode.ToString().Substring(6), out var wcsTaskCode);
            workTaskInfo.TaskCode = wcsTaskCode;
            //wms赋值
            workTaskInfo.WmsTaskCode = workTaskDto.TaskCode;
            workTaskInfo.DependWmsTaskCode = workTaskDto.DependWMSTaskCode;
            workTaskInfo.TaskType = Enum.Parse<EnumTaskType>(workTaskDto.TaskType.ToString());

            workTaskInfo.WmsFromPosition = workTaskDto.StartPosition;
            workTaskInfo.WmsToPosition = workTaskDto.EndPosition;
            workTaskInfo.WmsFromStation = workTaskDto.FromStation;
            workTaskInfo.WmsToStation = workTaskDto.ToStation;
            workTaskInfo.TaskProcessState = EnumTaskProcessState.Initial;
            workTaskInfo.TaskState = EnumTaskState.Executing;
            workTaskInfo.Priority = workTaskDto.Priority;

            //托盘条码
            workTaskInfo.PalletCode = plcMessage.PalletBarcode;




            #region 任务子任务信息赋值by RouteDetailInfo
            //获取配置巷道信息
            var routeConfigExp = Expressionable.Create<RouteInfo>();
            routeConfigExp.AndIF(true, (a) => a.FromStation == workTaskInfo.WmsFromStation && a.ToStation == workTaskInfo.WmsToStation);
            var routeInfo = await _workTaskInfoRepository.AsSugarClient()
                .Queryable<RouteInfo>()
                .Where(routeConfigExp.ToExpression())
                .Select((a) => new RouteInfo()
                {
                    ID = a.ID,
                    FromStation = a.FromStation,
                    ToStation = a.ToStation,
                }).FirstAsync();
            if (routeInfo == null)
            {
                runLogInfo.RunLog = $"起始工位{workTaskInfo.WmsFromStation}目标工位{workTaskInfo.WmsToStation}获取工位失败";
                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                return;
            }

            //巷道详情信息获取
            var routeDetailConfigExp = Expressionable.Create<RouteDetailInfo>();
            routeDetailConfigExp.AndIF(true, (a) => a.RouteID == routeInfo.ID && a.IsStart);
            var routeDetailInfo = await _workTaskInfoRepository.AsSugarClient()
                .Queryable<RouteDetailInfo>()
                .Where(routeDetailConfigExp.ToExpression())
                .Select((a) => new
                {
                    ID = a.ID,
                    RouteID = a.RouteID,
                    FromCargo = a.FromCargo,
                    ToCargo = a.ToCargo,
                    DispatchType = a.DispatchType,
                    FromEquipment = a.FromEquipment,
                    ToEquipment = a.ToEquipment,

                }).FirstAsync();

            if (routeDetailInfo == null)
            {
                runLogInfo.RunLog = $"巷道路径详情配置信息起始工位{workTaskInfo.WmsFromStation}目标工位{workTaskInfo.WmsToStation}获取设备路径失败";
                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                return;
            }

            workTaskInfo.CurrentToEquipment = routeDetailInfo.ToEquipment;

            workTaskInfo.CurrentFromCargo = routeDetailInfo.FromCargo;
            workTaskInfo.CurrentToCargo = routeDetailInfo.ToCargo;
            workTaskInfo.RouteID = routeDetailInfo.RouteID;
            workTaskInfo.CurrentRounteDetailID = routeDetailInfo.ID;
            workTaskInfo.CurrentDispatchType = routeDetailInfo.DispatchType;
            //起始设备位 
            workTaskInfo.CurrentFromEquipment = workTaskInfo.WmsFromPosition; //WMS 作业实际起点设备
                                                                              // workTaskInfo.CurrentToEquipment = routeDetailInfo.ToEquipment;
            workTaskInfo.CurrentDetailTaskState = EnumDetailTaskState.Executing;
            workTaskInfo.CurrentCreateTime = DateTime.Now;
            workTaskInfo.CurrentUpdateTime = DateTime.Now;
            #endregion

            workTaskInfo.SaveTime = DateTime.Now;
            workTaskInfo.UpdateTime = DateTime.Now;

            #region 同步更新wms任务状态&写入正常报文
            try
            {
                //同步更新wms任务状态为执行中
                var flag = await WCSMessageWithWMSApi.WCSUpdateWMStaskStateAndProcessTaskStateAsync(workTaskInfo.WmsTaskCode, (int)EnumTaskState.Executing);
                if (flag)
                {
                    workTaskInfo.UploadWmsState = EnumUploadWmsState.Succeed;
                    workTaskInfo.UploadWmsTime = DateTime.Now;
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("at") && ex.Message.Contains("System.Exception:"))
                {

                    var msg = ex.Message.Split("at").First().Split("System.Exception:");
                    runLogInfo.RunLog = $"任务号{workTaskInfo.WmsTaskCode}:向Wms同步状态更新失败:{msg[1]}";

                }
                else
                {
                    var msg = ex.Message.Length > 150 ? ex.Message.Substring(0, 100) : ex.Message;
                    runLogInfo.RunLog = $"任务号{workTaskInfo.WmsTaskCode}:向Wms同步状态更新失败:{msg}";
                }
                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
            }

            //WorkTaskInfo数据插入
            bool bl = await _workTaskInfoRepository.InsertAsync(workTaskInfo);

            //写入正常报文到Plc
            writeBo.TaskCode = workTaskInfo.TaskCode;//wcs任务号
            writeBo.ToEquipmentCode = workTaskInfo.CurrentToEquipment.ToInt32();//目标设备编号

            runLogInfo.RunLog = $"PLC写入报文内容： {JsonConvert.SerializeObject(writeBo)}";
            await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
            var writeResult = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());

            if (writeResult == false)
            {
                runLogInfo.RunLog = $"PLC(IP{plcConn.IP})写入报文失败";
                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                return;
            }
            else
            {
                runLogInfo.RunLog = $"PLC(IP{plcConn.IP})写入报文成功";
                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
            }
            #endregion

            #endregion

        }
    }
}
